import cquery from '@dfeidao/atom-nodejs/db/complex-query';
import format from '@dfeidao/atom-nodejs/dt/format';
import { IncomingHttpHeaders } from 'http';
import { file_url, systemid } from '../atom/config';

interface Message {
	filter: {
		teacher_no: string;
		start_time: number;
		end_time: number;
		productid: string;
	};
}

interface IWebResult {
	data: unknown;
	cookie?: {
		[name: string]: string;
	} | null;
	content_type?: string;
	headers?: {
		[key: string]: string[];
	};
	attachment?: string;
	redirect?: string;
	status_code?: number;
}

// _id	id	string
// record_no	记录编号	string
// teacher_no	教师编号	string
// teacher_name	教师姓名	string
// subject_num	科目编号	string
// subject_name	科目名称	string
// class_id	班级编号	string
// class_name	班级名称	string
// grade	年级名称	string
// grade_no	年级编号	string
// date	日期	timestamp
// week	星期	string
// section	节次	int
// productid	产品id	string
// recording_time	记录时间	timestamp
// start_time	开始时间	string
// finish_time	结束时间	string
interface ClassRecord {
	date: number;
	dates: string;
}

export default async function atom(message: Message, action_id: string, session_id: string, headers: IncomingHttpHeaders): Promise<IWebResult> {
	const cq = cquery(action_id, session_id, systemid);
	// 依据'日期'和‘教师编号’查询<上课记录>
	// '日期'对应<上课记录>中'日期'
	const class_record = await cq
		.add_field('class_record', 'teacher_name', 'teacher_name')
		.add_field('class_record', 'subject_name', 'subject_name')
		.add_field('class_record', 'class_name', 'class_name')
		.add_field('class_record', 'grade', 'grade')
		.add_field('class_record', 'class_id', 'class_id')
		.add_field('class_record', 'grade_no', 'grade_no')
		.add_field('class_record', 'section', 'section')
		.add_field('class_record', 'date', 'date')
		.add_field('class_record', 'teacher_no', 'teacher_no')
		.where_eq('class_record', 'teacher_no', message.filter.teacher_no)
		.where_gte('class_record', 'date', message.filter.start_time)
		.where_lte('class_record', 'date', message.filter.end_time)
		.where_eq('class_record', 'productid', message.filter.productid)
		.exec();
	const teacher: Array<{ headimg: string, url_img: {}, productid: string }> = await cq
		.add_field('teacher', 'headimg', 'headimg')
		.add_field('teacher', 'productid', 'productid')
		.where_eq('teacher', 'teacher_no', message.filter.teacher_no)
		.exec();
	if (class_record.length > 0) {
		class_record.forEach((i: ClassRecord) => {
			i.dates = format(i.date, 'YYYY-MM-DD aa');
		});
	}
	if (teacher.length > 0) {
		teacher[0].url_img = teacher[0].headimg ? {
			uri: file_url + '/getfile?productid=' + message.filter.productid + '&id=' + teacher[0].headimg
		} : '';
	}
	return { data: { class_record, teacher } } as IWebResult;
}
